<template>
	<div>
		<div class="container">
			<div class="toolbar">
				<a-form ref="searchRef" layout="inline" :model="searchState" @finish="loading = true; initData()">
					<a-form-item label="公司筛选">
						<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择项目" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
					</a-form-item>
					<a-form-item label="选择项目">
						<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" allow-clear></a-select>
					</a-form-item>
					<a-form-item label="筛选字段">
						<a-select v-model:value="searchState.args" style="min-width: 100px" mode="tags" :show-search="true" :options="argOptions" option-filter-prop="label" allow-clear></a-select>
					</a-form-item>
					<a-form-item>
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>
						</a-space>
					</a-form-item>
					<a-form-item>
						<a-space>
							<a-button v-permission="195" @click="exportAll">
								<download-outlined />导出
							</a-button>
						</a-space>
					</a-form-item>
				</a-form>
			</div>
			<div class="mt-2">
				<a-table :columns="innerColumns" :scroll="tableScroll" children-column-name="children" :default-expand-all-rows="false" :data-source="pageSources" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, index }">
						<template v-if="column.dataIndex === 'project_id'">
							<a-space>
								<a-select v-model:value="pageSources[index].project_id" :options="projectOptions" option-filter-prop="label" disabled></a-select>
							</a-space>
						</template>
						<template v-if="column.dataIndex === 'company_id' && pageSources[index].company_id">
							<a-space>
								<a-select v-model:value="pageSources[index].company_id" :options="companyOptions" option-filter-prop="label" disabled></a-select>
							</a-space>
						</template>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup>
import { post } from "../utils/index.js";
import { computed, getCurrentInstance, reactive, ref } from "vue";
import { DownloadOutlined } from "@ant-design/icons-vue";

import { exportData } from "@/utils/exportData.js";
const searchRef = ref();
const searchState = reactive({
	args: []
});
const formState = ref({});
const formRef = ref();
const pageSources = ref([]);
const loading = ref(false);
const { proxy } = getCurrentInstance();
const projectOptions = ref([]);
const companyOptions = ref([]);
const argOptions = ref([]);
const pagination = ref({
	current: 1,
	pageSize: 10,
	total: 0
});
const initProjects = new Promise((resolve, reject) => {
	post("department/projects?type=3").then(({ data }) => {
		projectOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
		resolve();
	});
});
const initCompany = new Promise((resolve, reject) => {
	post("department/projects?type=2", {
		parent_ids: JSON.stringify([78, 24])
	}).then(({ data }) => {
		companyOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
		resolve();
	});
});
Promise.all([initProjects, initCompany]).then(() => {
	initData();
});

const columns = ref([]);
const innerColumns = computed(() => {
	if (!searchState.args.length) {
		return columns.value;
	}
	return columns.value.filter(item => {
		return item.fixed || searchState.args.includes(item.dataIndex);
	});
});
post("data/all").then(({ data }) => {
	for (const d of data) {
		if (!d.show) continue;
		const item = {
			title: d.data_name,
			dataIndex: d.data_key,
			sorter: false,
			width: 150,
			ellipsis: true
		};
		if (d.read_only) {
			item.fixed = "left";
		} else {
			argOptions.value.push({
				value: d.data_key,
				label: d.data_name
			});
		}
		if (d.data_key === "index") {
			item.width = 100;
			item.customRender = ({ text, record, index, column }) => {
				return index + 1;
			};
		}
		columns.value.push(item);
	}
	columns.value.push({
		title: "录入用户",
		dataIndex: "fullname",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "right",
		customRender: ({ text, record, index, column }) => {
			return text;
		}
	});
});
const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 650
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: pagination.value.current,
			pageSize: pagination.value.pageSize
		},
		pag || {}
	);
	loading.value = true;
	const searchProjectId = searchState.project_id;
	const searchCompanyId = searchState.company_id;
	post("dataRecords/all", {
		page: pag.current,
		size: pag.pageSize,
		project_id: searchProjectId,
		company_id: searchCompanyId
	})
		.then(({ data, total }) => {
			const list = [];
			for (const item of data) {
				list.push({
					...item.record,
					id: item.id,
					fullname: item.user?.fullname
				});
			}
			pageSources.value = list;
			pagination.value = {
				...pag,
				total
			};
		})
		.finally(() => {
			loading.value = false;
		});
};

const exportAll = async () => {
	const { data } = await post("dataRecords/all", { project_id: searchState.project_id });
	const columns = innerColumns.value;
	const dataSource = [];
	const project2Id = projectOptions.value.reduce((target, item) => {
		target[item.value] = item.label;
		return target;
	}, {});
	const company2Id = companyOptions.value.reduce((target, item) => {
		target[item.value] = item.label;
		return target;
	}, {});
	for (let i = 0; i < data.length; i++) {
		const record = data[i].record;
		const rowData = {
			index: i + 1,
			project_id: project2Id[record.project_id],
			company_id: company2Id[record.company_id] || ""
		};

		/* eslint-disable */
		for (const key in record) {
			switch (key) {
				case "project_id":
					rowData[key] = project2Id[record.project_id];
					break;
				case "company_id":
					rowData[key] = company2Id[record.company_id] || "";
					break;
				case "index":
					rowData[key] = i + 1;
					break;
				default:
					rowData[key] = record[key];
					break;
			}
		}
		/* eslint-enable */

		rowData.fullname = data[i].user.fullname;
		dataSource.push(rowData);
	}
	exportData(columns, dataSource, `file.xlsx`);
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
